<template>
    <div class="pnl upload-list ghost-upload">
        <div class="item ghost-item" v-for="(item, index) in uploadList" :key="index" v-show="item.imgUrl">
            <template>
                <a :href="preFixPath + item.imgUrl" target="_blank"><img :src="preFixPath + item.imgUrl + '_110w'"></a>
                <Icon class="btn-close" type="md-close-circle" @click.native="removeUploadItem"></Icon>
            </template>
        </div>
        <Upload
            v-show="uploadList.length === 0 || uploadList[0].imgUrl === ''"
            ref="upload"
            :show-upload-list="false"
            :on-success="onUploadSuccess"
            :accept="accept"
            :format="format"
            :max-size="uploadMax"
            :on-format-error="onUploadFormatError"
            :on-exceeded-size="onUploadSizeError"
            type="drag"
            :headers="headers"
            :action="uploadImageUrl">
            <Button icon="ios-cloud-upload-outline">上传</Button>
        </Upload>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { uploadImageUrl, preFixPath } from "@/util"

export default {
  props: {
    uploadList: {
      type: Array,
      default: []
    },
    maxlength: {
      type: Number,
      default: 1
    },
    index: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      uploadImageUrl,
      preFixPath,
			format: SYSTEM_CONFIG.uploadImageExtensions,
      uploadMax: SYSTEM_CONFIG.uploadMaxSize * 1024,
      headers: {}
    };
  },
  mounted() {
    let userToken = this.user.userToken
    if (userToken){
      this.headers['Authorization'] = 'Bearer ' + `${userToken}`;
    }
  },
	computed: {
    ...mapGetters(['user']),
    accept() {
      let acceptStr = SYSTEM_CONFIG.uploadImageExtension.split(',').map(item => 'image/'+item).join(',');   
      return acceptStr
    }
	},
  methods: {
    removeUploadItem() {
      this.$emit("uploadPic", this.index, {imgUrl: ''})
      this.$refs.upload.fileList.splice(0, 1)
    },
    onUploadSuccess(res, file) {
      if (res.code === 200) {
        file.url = res.data;
        let path = res.data.path;
        file.imgUrl = path;
        this.$Message.success("上传成功")
        // this.$set(this.uploadList, 0, file)
      } else {
        this.$Notice.error({
          title: "上传失败",
          desc: res.message
        });
        this.$refs.upload.fileList.splice(0, 1)
      }
      this.$emit("uploadPic", this.index, file);
    },
    onUploadFormatError(file) {
      this.$Notice.warning({
        title: "文件格式不正确",
        desc:
          "文件 " + file.name + " 格式不正确，请上传 jpg 或 png 格式的图片。"
      })
    },
    onUploadSizeError(file) {
      this.$Notice.warning({
        title: "超出文件大小限制",
        desc: "文件 " + file.name + " 太大，不能超过 4M。"
      })
    }
  }
};
</script>
